package com.eliza.base.entity.model.livedata

import androidx.lifecycle.LiveData
import androidx.lifecycle.MutableLiveData
import androidx.lifecycle.ViewModel
import androidx.lifecycle.liveData
import androidx.lifecycle.viewModelScope
import com.eliza.library.data.entity.UserEntity
import dagger.hilt.android.lifecycle.HiltViewModel
import kotlinx.coroutines.flow.MutableStateFlow
import kotlinx.coroutines.flow.SharingStarted.Companion.WhileSubscribed
import kotlinx.coroutines.flow.StateFlow
import kotlinx.coroutines.flow.flow
import kotlinx.coroutines.flow.stateIn
import kotlinx.coroutines.launch
import javax.inject.Inject


@HiltViewModel
class LiveViewModel @Inject constructor() : ViewModel() {
    private val _myMLiveData = MutableLiveData<List<UserEntity>>(emptyList())
    val myUiLiveData: LiveData<List<UserEntity>> = _myMLiveData

    private val _myMFlow = MutableStateFlow<List<UserEntity>>(emptyList())
    val myUiFlow: MutableStateFlow<List<UserEntity>> = _myMFlow

    // 公开一次性
    val _myLiveData: LiveData<List<UserEntity>> = liveData {
        emit(listOf(UserEntity(1, "a", "a")))
    }

    val result: StateFlow<List<UserEntity>> = flow {
        emit(listOf(UserEntity(1, "a", "a")))
    }.stateIn(
        scope = viewModelScope,
        started = WhileSubscribed(5000), // 或者 Lazily，因为它是一次性的
        initialValue = listOf(
            UserEntity(0, "0", "0")
        )
    )
//    3: 带参的 一次性数据 加载


    // 从 suspend fun 加载数据并转变状态
    init {
        viewModelScope.launch {
            val result = listOf(
                UserEntity(1, "a", "a"),
                UserEntity(2, "b", "b")
            )
            _myMLiveData.value = result
        }
    }

}